<?php
require_once 'common/config.php';
require_once 'common/functions.php';

// 检查登录状态
check_login();

// 初始化数据库连接
$db = db_connect();

// 检查是否已达到最大数量限制
$stmt = $db->query("SELECT COUNT(*) FROM banners");
$count = $stmt->fetchColumn();
if ($count >= 5) {
    redirect('banners.php', '轮播图数量已达到上限', 'error');
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $link_url = trim($_POST['link_url']);
    $sort_order = intval($_POST['sort_order']);
    $status = isset($_POST['status']) ? 1 : 0;

    // 处理文件上传
    if (!empty($_FILES['image']['name'])) {
        $target_dir = "../api/user/uploads/banners/";
        // 确保目录存在
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }

        $imageFileType = strtolower(pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION));
        $new_filename = date('Ymd_His') . '_' . uniqid() . '.' . $imageFileType;
        $target_file = $target_dir . $new_filename;

        // 检查文件类型
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($imageFileType, $allowed_types)) {
            if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
                $image_url = 'uploads/banners/' . $new_filename;
            } else {
                redirect('banner_add.php', '文件上传失败，请重试。', 'error');
                exit();
            }
        } else {
            redirect('banner_add.php', '只允许上传 JPG, JPEG, PNG 和 GIF 文件。', 'error');
            exit();
        }
    } else {
        redirect('banner_add.php', '请选择要上传的图片。', 'error');
        exit();
    }

    try {
        // 插入数据库
        $stmt = $db->prepare("INSERT INTO banners (image_url, title, link_url, sort_order, status, create_time) VALUES (:image_url, :title, :link_url, :sort_order, :status, NOW())");
        $stmt->bindValue(':image_url', $image_url);
        $stmt->bindValue(':title', $title);
        $stmt->bindValue(':link_url', $link_url);
        $stmt->bindValue(':sort_order', $sort_order);
        $stmt->bindValue(':status', $status);
        
        if ($stmt->execute()) {
            redirect('banners.php', '添加成功');
        } else {
            redirect('banner_add.php', '添加失败，请重试。', 'error');
        }
    } catch (Exception $e) {
        redirect('banner_add.php', '系统错误：' . $e->getMessage(), 'error');
    }
}

// 获取当前最大排序值
$stmt = $db->query("SELECT MAX(sort_order) FROM banners");
$max_sort = $stmt->fetchColumn();
$next_sort = $max_sort ? $max_sort + 1 : 1;
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加轮播图 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
    .card {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        padding: 25px;
    }
    .preview-image {
        max-width: 300px;
        max-height: 150px;
        object-fit: cover;
        border-radius: 4px;
        margin-top: 10px;
    }
    .form-group {
        margin-bottom: 20px;
    }
    .form-control {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        transition: border-color 0.3s;
    }
    .form-control:focus {
        border-color: #3498db;
        outline: none;
    }
    .help-text {
        font-size: 12px;
        color: #666;
        margin-top: 5px;
    }
    </style>
</head>
<body>
    <div class="wrapper">
        <?php include 'includes/sidebar.php'; ?>
        
        <div class="main-content">
            <header class="top-header">
                <div class="header-left">
                    <h2>添加轮播图</h2>
                </div>
                <div class="header-right">
                    <a href="banners.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left"></i> 返回列表
                    </a>
                </div>
            </header>

            <div class="content">
                <div class="card">
                    <form action="" method="POST" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="title">标题</label>
                            <input type="text" id="title" name="title" class="form-control" required>
                        </div>

                        <div class="form-group">
                            <label for="image">轮播图片</label>
                            <input type="file" name="image" id="image" class="form-control" accept="image/*" required>
                            <div class="help-text">建议尺寸：1920×600，支持 jpg, jpeg, png, gif 格式</div>
                            <div class="image-preview"></div>
                        </div>

                        <div class="form-group">
                            <label for="link_url">链接地址</label>
                            <input type="text" id="link_url" name="link_url" class="form-control" required>
                            <div class="help-text">例如：/pages/guide-detail/guide-detail?id=1</div>
                        </div>

                        <div class="form-group">
                            <label for="sort_order">排序</label>
                            <input type="number" id="sort_order" name="sort_order" class="form-control" 
                                   value="<?php echo $next_sort; ?>" min="1" max="5" required>
                            <div class="help-text">数字越小越靠前，范围：1-5</div>
                        </div>

                        <div class="form-group">
                            <label>
                                <input type="checkbox" name="status" value="1" checked>
                                启用轮播图
                            </label>
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
    // 图片预览功能
    document.getElementById('image').onchange = function(e) {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.querySelector('.image-preview');
                preview.innerHTML = `<img src="${e.target.result}" class="preview-image">`;
            }
            reader.readAsDataURL(file);
        }
    };
    </script>
</body>
</html> 